package com.ruoyi.web.controller.chongyuhui;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.chongyuhui.TbSwipperEntity;
import com.ruoyi.system.mapper.chongyuhui.TbSwipperMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author:JiangJiang
 */
@RestController
public class SwipperController {

    @Autowired
    TbSwipperMapper swipperMapper;

    String preUrl = "/dev-api";

    /**
     * .新增图片
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("uploadSwipper")
    public AjaxResult uploadSwip(MultipartFile file) throws IOException {

        String url = FileUploadUtils.upload(file);

        // 保存到数据库
        String title = file.getOriginalFilename();
        TbSwipperEntity entity = new TbSwipperEntity();
        entity.setSrc("/api/profile" + url);
        entity.setTitle(title);
        swipperMapper.insert(entity);
        return AjaxResult.success();
    }

    @PostMapping("deleteSwipper")
    public AjaxResult deleteSwipper(@RequestBody TbSwipperEntity entity) throws IOException {

        // 删除数据库
        swipperMapper.delete(entity);

        // 删除本地文件
        FileUtils.deleteFile(FileUploadUtils.getDefaultBaseDir() + entity.getSrc().replace(preUrl, "").replace(Constants.RESOURCE_PREFIX, ""));

        return AjaxResult.success();
    }



}
